Dates


JavaScript provides the Date object to work with dates and times. The Date object is used to create, manipulate, and format dates and times.

1. Creating Dates

Dates can be created using the Date constructor:

const now = new Date(); // Current date and time
const specificDate = new Date('2024-09-27'); // Specific date
const dateTime = new Date('2024-09-27T14:00:00'); // Specific date and time
const timestamp = new Date(1632740400000); // Date from timestamp

2. Getting Date and Time Components

The Date object provides methods to get various components of a date and time:

const now = new Date();
console.log(now.getFullYear());
console.log(now.getMonth()); // months are zero-indexed
console.log(now.getDate()); 
console.log(now.getHours()); 
console.log(now.getMinutes());
console.log(now.getSeconds()); 
console.log(now.getMilliseconds()); 
console.log(now.getDay());   //( days are zero-indexed starting from Sunday)

3. Setting Date and Time Components

The Date object provides methods to set various components of a date and time:

const now = new Date();
now.setFullYear(2025);
now.setMonth(0); // January
now.setDate(1);
now.setHours(12);
now.setMinutes(30);
now.setSeconds(45);
console.log(now); // Outputs: 2025-01-01T07:00:45.000Z (depending on your time zone)

4. Formatting Dates

JavaScript provides methods to format dates as strings:

const now = new Date();
console.log(now.toDateString()); 
console.log(now.toTimeString()); 
console.log(now.toLocaleDateString()); 
console.log(now.toLocaleTimeString()); 
console.log(now.toISOString());

5. Date Arithmetic

JavaScript allows you to perform arithmetic operations on dates:

const now = new Date();
const tomorrow = new Date(now);
tomorrow.setDate(now.getDate() + 1);
console.log(tomorrow);

const nextWeek = new Date(now);
nextWeek.setDate(now.getDate() + 7);
console.log(nextWeek);